<template>
  <div class="avatar-manage">
    <div class="avatar-manage__img">
      <img
        :src="userStore.user.avatar"
        alt=""
        @click="openModal(userStore.user.avatar)"
      />
    </div>
    <div class="updateload-avatar">
      <avatar-upload
        ref="uploadRef"
        action="/api/user/updateAvatar"
        @start="startUpload"
        @success="uploadSuccess"
        @error="uploadError"
      >
        <el-button
          class="updateload-avatar__button"
          type="primary"
          @click="openFolder"
          :loading="isLoading"
          :disabled="isLoading"
          ><template #loading><Loading /></template>更改</el-button
        >
      </avatar-upload>
    </div>
  </div>
  <Modal v-model="showModal">
    <img class="img-browser" :src="imgSrc" alt="" />
  </Modal>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { useUserPinia } from "@/pinia/user";
import avatarUpload from "@/components/ui-components/avatarUpload.vue";
import { ElMessage } from "element-plus";
import Modal from "@/components/ui-components/modal.vue";

const userStore = useUserPinia();

/**
 * 给头像上传组件一个ref属性
 */
const uploadRef = ref<typeof avatarUpload>();

// 点击更改按钮打开文件夹
const openFolder = () => uploadRef.value?.upload();

/**
 * 是否正在上传文件
 */
const isLoading = ref<boolean>(false);

/**
 * 开始上传头像的操作
 */
const startUpload = () => (isLoading.value = true);

/**
 * 上传头像成功后的操作
 * @param src - 新头像的url
 */
const uploadSuccess = (src: string) => {
  userStore.user.avatar = src;
  isLoading.value = false;
  ElMessage.success("上传成功");
};

/**
 * 上传头像失败后的操作
 */
const uploadError = () => {
  isLoading.value = false;
  ElMessage.error("上传失败");
};

/**
 * 当前用户查看的图片的url
 */
const imgSrc = ref<string>("");
/**
 * 是否显示模态框
 */
const showModal = ref<boolean>(false);
// 浏览图片时打开模态框
const openModal: (url: string) => void = (url: string): void => {
  imgSrc.value = url;
  showModal.value = true;
};
</script>

<style lang="scss" scoped>
.avatar-manage {
  &__img {
    text-align: center;

    img {
      @include setWidHei(60px, 60px);
      @include noselect();
      object-fit: cover;
      cursor: pointer;
    }
  }
}

.updateload-avatar {
  margin: 30px 0;
  text-align: center;

  &__button {
    width: 100px;
  }
}
</style>
